/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.peng.domain.RecyclerUser;
import me.peng.domain.config.SysResult;
import me.peng.domain.mapper.RecyclerUserMpper;
import me.peng.utils.ValidationUtil;
import me.peng.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.peng.repository.RecyclerUserRepository;
import me.peng.service.RecyclerUserService;
import me.peng.service.dto.RecyclerUserDto;
import me.peng.service.dto.RecyclerUserQueryCriteria;
import me.peng.service.mapstruct.RecyclerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.peng.utils.PageUtil;
import me.peng.utils.QueryHelp;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author pengjianye
* @date 2021-09-30
**/
@Service
@RequiredArgsConstructor
public class RecyclerUserServiceImpl implements RecyclerUserService {

    private final RecyclerUserRepository recyclerUserRepository;
    private final RecyclerUserMapper recyclerUserMapper;
    @Autowired
    RecyclerUserMpper recyclerUserMpper2;
    @Override
    public Map<String,Object> queryAll(RecyclerUserQueryCriteria criteria, Pageable pageable){
        Page<RecyclerUser> page = recyclerUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(recyclerUserMapper::toDto));
    }

    @Override
    public List<RecyclerUserDto> queryAll(RecyclerUserQueryCriteria criteria){
        return recyclerUserMapper.toDto(recyclerUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public RecyclerUserDto findById(Integer id) {
        RecyclerUser recyclerUser = recyclerUserRepository.findById(id).orElseGet(RecyclerUser::new);
        ValidationUtil.isNull(recyclerUser.getId(),"RecyclerUser","id",id);
        return recyclerUserMapper.toDto(recyclerUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecyclerUserDto create(RecyclerUser resources) {
        return recyclerUserMapper.toDto(recyclerUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RecyclerUser resources) {
        RecyclerUser recyclerUser = recyclerUserRepository.findById(resources.getId()).orElseGet(RecyclerUser::new);
        ValidationUtil.isNull( recyclerUser.getId(),"RecyclerUser","id",resources.getId());
        recyclerUser.copy(resources);
        recyclerUserRepository.save(recyclerUser);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            recyclerUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RecyclerUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RecyclerUserDto recyclerUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", recyclerUser.getUsername());
            map.put("电话号码", recyclerUser.getPhone());
            map.put("性别", recyclerUser.getSex());
            map.put("积分", recyclerUser.getPoint());
            map.put("创建时间", recyclerUser.getCreateDate());
            map.put("更新时间", recyclerUser.getRenewDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }



    /**
     * 电话号码查询
     * @return
     */
    @Override
    public int findByPhone(RecyclerUser phone) {

        QueryWrapper<RecyclerUser> queryWrapper=new QueryWrapper<>(phone);
        RecyclerUser user=recyclerUserMpper2.selectOne(queryWrapper);
        if (user==null){
            return 0;
        }
        return 1;
    }
    /**
     * 添加手机号码
     * @param user
     * @return
     */
    @Override
    public SysResult registerAddUser(@RequestBody RecyclerUser user) {
        recyclerUserMpper2.insert(user);
        return SysResult.success();
    }

    /**
     * 根据手机号码查询此列的所有信息
     * @return
     */
    @Override
    public SysResult selectPhoneList(RecyclerUser phone) {

        QueryWrapper<RecyclerUser> queryWrapper=new QueryWrapper<>(phone);
        RecyclerUser user=recyclerUserMpper2.selectOne(queryWrapper);

        return SysResult.success(user);
    }

    //修改用户信息
    @Override
    public void updateUserInfo(RecyclerUser user) {
        //传递的为商品所需积分，用户购买商品，减去用户积分值
        if (user.getPoint()!=null){
            RecyclerUser recyclerUser=recyclerUserMpper2.selectById(user.getId());
            int point=recyclerUser.getPoint();
            int comPonit=user.getPoint();
            if (point>=comPonit){
                int newPoint=point-comPonit;
                user.setPoint(newPoint);
            }
        }

        recyclerUserMpper2.updateById(user);
    }
}
